#include "Thread.hpp"
#include <vector>

int ticketnum = 10000;
void Ticket(ThreadModule::ThreadData *td)
{
    while(true)
    {
        pthread_mutex_lock(td->_lock_ptr);      // 加锁
        if(ticketnum > 0)
        {
            // 抢票
            printf("get a new ticket, who get it: %s, id: %d\n", td->_name.c_str(), ticketnum--);
            pthread_mutex_unlock(td->_lock_ptr);// 解锁
        }
        else
        {
            pthread_mutex_unlock(td->_lock_ptr);// 解锁
            break;
        }
    }
}
#define NUM 4
int main()
{
    // 创建局部锁
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, nullptr);
    // 创建线程对象
    std::vector<ThreadModule::Thread> threads;
    for(int i = 0;i < NUM; i++)
    {
        std::string name = "thread-" + std::to_string(i+1);
        // 把锁的地址给到td对象
        ThreadModule::ThreadData *td = new ThreadModule::ThreadData(name, &mutex);
        // 之后在将td给到Thread
        threads.emplace_back(name, Ticket, td);
    }
    // 启动线程
    for(int i = 0; i< NUM;i++)
        threads[i].Start();
    // 等待线程
    for(int i = 0; i< NUM;i++)
        threads[i].Join();
    // 释放锁
    pthread_mutex_destroy(&mutex);  
    return 0;
}